from typing import List
from app.api.deps import CurrentUser, SessionDep
from app.crud import get_devices_by_user_id
from app.models import BatchExecuteScriptsReq, Device, DeviceListResponse
from app.websocket_manager import ManagerDep
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from loguru import logger

router = APIRouter(prefix="/device", tags=["device"])


@router.get("/", response_model=DeviceListResponse)
def get_devices_api(
    session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> List[Device]:
    if current_user.is_superuser:
        count_statement = select(func.count()).select_from(Device)
        count = session.exec(count_statement).one()
        statement = select(Device).offset(skip).limit(limit).order_by(Device.id)
        items = session.exec(statement).all()
    else:
        count_statement = (
            select(func.count())
            .select_from(Device)
            .where(Device.user_id == current_user.id)
        )
        count = session.exec(count_statement).one()
        statement = (
            select(Device)
            .where(Device.user_id == current_user.id)
            .offset(skip)
            .limit(limit).order_by(Device.id)
        )
        items = session.exec(statement).all()

    return DeviceListResponse(data=items, count=count)


@router.get("/scripts/{device_id}")
async def get_scripts_by_device_id(
    device_id: int,
    req_id: str,
    current_user: CurrentUser,
    session: SessionDep,
    socket_manager: ManagerDep,
):
    logger.info(f"Getting scripts for device {device_id}, request ID: {req_id}")
    devices = get_devices_by_user_id(session, current_user.id)
    if current_user.is_superuser or devices:
        socket_manager.add_queue(req_id)
        await socket_manager.broadcast_to(
            device_id, {"event": "refresh_scripts_list", "reqId": req_id}
        )
        return await socket_manager.get_resp_data(req_id)


@router.post("/batchExecuteScripts/{device_id}")
async def batch_exexute_scripts(
    device_id: int,
    data: BatchExecuteScriptsReq,
    session: SessionDep,
    socket_manager: ManagerDep,
):  
    logger.info(data)
    logger.info(device_id)
    try:
        await socket_manager.broadcast_to(
            device_id, {"event": "batch_execute_scripts", "data": data.model_dump()}
        )
        # 返回标准成功响应
        return {
            "success": True,
            "message": "Scripts executed successfully",
            "device_id": device_id,
        }

    except Exception as e:
        logger.error(f"Error executing scripts: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")

@router.post("/stopExecuteScript/{device_id}")
async def stop_execute_script(device_id: int, socket_manager: ManagerDep):
    try:
        await socket_manager.broadcast_to(
            device_id, {"event": "stop_batch_execute_scripts"}
        )
        # 返回标准成功响应
        return {
            "success": True,
            "message": "Scripts stopped successfully",
            "device_id": device_id,
        }

    except Exception as e:
        logger.error(f"Error stopping scripts: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")